package com.example.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.example.bean.Result;
import com.example.dto.PwdDto;
import com.example.dto.UserDto;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import com.example.utils.Md5Util;
import com.example.utils.ThreadLocalUtil;
import com.example.vo.UserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author weijingchen
 * @DateTime 2025-09-24
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public Result register(UserDto dto) {
        User user = userMapper.getByUsername(dto.getUsername());
        if (ObjectUtils.isEmpty(user)) {
            log.info("用户不存在，开始注册");
            String md5String = Md5Util.getMD5String(dto.getPassword());
            User newUser = BeanUtil.copyProperties(dto, User.class);
            newUser.setPassword(md5String);
            userMapper.insert(newUser);
            return Result.success("注册成功");
        } else {
            return Result.error("用户已存在");
        }
    }

    @Override
    public Result login(UserDto dto) {
        User user = userMapper.getByUsername(dto.getUsername());
        if (!ObjectUtils.isEmpty(user)) {
            boolean flag = Md5Util.checkPassword(dto.getPassword(), user.getPassword());
            if (flag) {
                HashMap<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("username", user.getUsername());
                String token = JwtUtil.genToken(claims);
                // 保存token 设置过期时间是1小时
                //todo 后期配置到yml文件中
                redisTemplate.opsForValue().set("Authorization:" + user.getId(), token, 12, TimeUnit.HOURS);
                return Result.success(token);
            } else {
                return Result.error("密码错误");
            }
        } else {
            return Result.error("用户不存在");
        }
    }

    @Override
    public UserVo getById(Integer id) {
        User user = userMapper.getById(id);
        if (!ObjectUtils.isEmpty(user)) {
            return BeanUtil.copyProperties(user, UserVo.class);
        } else {
            return new UserVo();
        }
    }

    @Override
    public Result update(UserDto dto) {
        User user = BeanUtil.copyProperties(dto, User.class);
        user.setId(ThreadLocalUtil.getId());
        int updatedRows = userMapper.update(user);
        if (updatedRows > 0) {
            return Result.success();
        } else {
            return Result.error("更新失败");
        }
    }

    @Override
    public Result updateAvatar(String avatar) {
        userMapper.updateAvatar(ThreadLocalUtil.getId(), avatar);
        return Result.success();
    }

    @Override
    public Result updatePWD(PwdDto dto) {
        if (!dto.getNewPwd().equals(dto.getRePwd())) {
            return Result.error("两次密码不一致");
        }
        User user = userMapper.getById(ThreadLocalUtil.getId());
        if (!ObjectUtils.isEmpty(user)) {
            boolean flag = Md5Util.checkPassword(dto.getOldPwd(), user.getPassword());
            if (flag) {
                String md5String = Md5Util.getMD5String(dto.getNewPwd());
                userMapper.updatePWD(ThreadLocalUtil.getId(), md5String);
                redisTemplate.delete("Authorization:" + ThreadLocalUtil.getId());
                return Result.success();
            } else {
                return Result.error("旧密码错误");
            }
        } else {
            return Result.error("登录失效");
        }
    }
}
